package com.bigfans.catalogservice.service.brand;

import com.bigfans.catalogservice.dao.BrandDAO;
import com.bigfans.catalogservice.model.Brand;
import com.bigfans.framework.Applications;
import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.event.ApplicationEventBus;
import com.bigfans.framework.model.SystemSetting;
import com.bigfans.framework.plugins.FileStoragePlugin;
import com.bigfans.framework.plugins.PluginManager;
import com.bigfans.framework.plugins.UploadResult;
import com.bigfans.framework.utils.BeanUtils;
import com.bigfans.model.event.BrandCreatedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;

/**
 * 
 * @Title: 
 * @Description: 品牌服务类
 * @author lichong 
 * @date 2015年12月13日 下午6:07:41 
 * @version V1.0
 */
@Service(BrandServiceImpl.BEAN_NAME)
public class BrandServiceImpl extends BaseServiceImpl<Brand> implements BrandService {

	public static final String BEAN_NAME = "brandService";
	
	private BrandDAO brandDAO;

	@Autowired
	private ApplicationEventBus applicationEventBus;
	
	@Autowired
	public BrandServiceImpl(BrandDAO brandDAO) {
		super(brandDAO);
		this.brandDAO = brandDAO;
	}

	@Override
	@Transactional
	public void create(Brand e) throws Exception {
		super.create(e);
		BrandCreatedEvent event = new BrandCreatedEvent();
		BeanUtils.copyProperties(e , event);
		applicationEventBus.publishEvent(event);
	}

	public UploadResult uploadLogo(InputStream is , String imageExtension) throws Exception {
		SystemSetting setting = Applications.getSystemSetting();
		String imageServer = setting.getImageStoragePlugin();
		FileStoragePlugin storagePlugin = PluginManager.getFileStoragePlugin(imageServer);
		String targetFileName = "logo_" + System.currentTimeMillis() + "_" + imageExtension;
		String key = "images/brand/"+targetFileName;
		UploadResult uploadResult = storagePlugin.uploadFile(is , key);
		return uploadResult;
	}
	
	public UploadResult deleteLogo(String imgPath) throws Exception {
		SystemSetting setting = Applications.getSystemSetting();
		String imageServer = setting.getImageStoragePlugin();
		FileStoragePlugin storagePlugin = PluginManager.getFileStoragePlugin(imageServer);
		UploadResult uploadResult = storagePlugin.deleteFile(imgPath);
		return uploadResult;
	}
	
}
